window.addEventListener("click", function(event) {
	if((event.target.id == "popup" || event.target.className == "btnClose") && $id("loadingView").hasClass("hide")) {
		hidePopup();
	} 
});



function setEvents() {
	$id("home").addEventListener("click", function() {
		showPage("content-index");
		callServiceHotBook();
	});

	$id("books").addEventListener("click", function() {		
		showPage("content-category");
		setPageServiceAllBook();
	});

    $id("about").addEventListener("click", function() {
		showPage("aboutView");
        callServiceInformation();
    });

    $id("btnFeedBack").addEventListener("click", function() {
		showPage("contactView",true);
		$id("feedBackEmailId").value=currentUserEmail;
	});

    window.addEventListener("keypress", function (e) {
    if (e.keyCode == 13) {
        showPage("content-category")
		var key = $id("searchBar").value;
		setPageServiceAllBook(0, key);
    }
    });

	$id("categoryFirst").addEventListener("click", callFirst);
	$id("categoryLast").addEventListener("click", callLast);
	$id("categoryPrevious").addEventListener("click", callPrevious);
	$id("categoryNext").addEventListener("click", callNext);

	$id("btnSearch").addEventListener("click", function() {
        showPage("content-category")
		var key = $id("searchBar").value;
		setPageServiceAllBook(0, key);
	}); 




	$id("btnRegister").addEventListener("click", function() {
		//pagesManager.setPage(Pages.registerUser, true);
		showPage("registerUser",true);
	});
	
	$id("btnRegisterId").addEventListener("click",function(){
		registerUseronClick();
		return false;
	});

    $id("cart-content").addEventListener("click", function() {
       // pagesManager.setPage(Pages.cart, false);
        if(CartFunction.getCartFromSessionStorage().length > 0) {
            CartFunction.openCart();
            showPage("cartView", false);
        } else {
            alert("Your cart is empty!");
        }
    });
    
    $id("btnCmt").addEventListener("click", function(){
    	addComment();
    })

	$id("btnLogin").addEventListener("click", function() {
		//event.preventDefault();
		if ($id("panel").hasClass("hide")) {
			$id("panel").removeClass("hide");
			$id("btnLogin").addClass("activeHeader");
		} else {
			$id("panel").addClass("hide");
			$id("btnLogin").removeClass("activeHeader");
		}
	});

	$id("btnSignIn").addEventListener("click", function(event) {
		//event.preventDefault();
		var textbox = document.getElementById("txtCmt");
		var commentText = textbox.value;
		var bookId = textbox.getAttribute("bookid");

		var userName = $id("txtNickName").value;
		var password = $id("txtPass").value;
		ajax.post({
			url : "http://localhost:8080/book-service/public/book/authen/login",
			param : {
				"userName" : userName,
				"passWord" : password
			},

			success : function(data, xhr) {
				console.log(data);

				$id("login").addClass("hide");
				$id("profile").removeClass("hide");
				$id("panel").addClass("hide");
			var avatar = data.getElementsByTagName("avatar")[0].childNodes[0].nodeValue;
			
	        $id("profileUserName").innerText= userName.substring(0,5);
	   		$id("icon-avatar").src =avatar;
	        $id("profilePicture").src= avatar;
				$id("profileUserName").innerText = userName.substring(0, 5);
				$id("icon-avatar").src = avatar;
				$id("profilePicture").src = avatar;
				
			currentUserEmail = data.getElementsByTagName("email")[0].childNodes[0].nodeValue;
			currentUserId = userName;	
			},
			failure : function(xhr) {
				alert("tên đăng nhập hoặc mật khẩu không đúng!");
				pagesManager.hideLoading();
			},
			abort : function(xhr) {
				callback.abort(xhr);
			}
		});

	});

	$id("myProfileId").addEventListener("click", function(event) {
		/*
		 event.preventDefault();
		 pagesManager.setPage(Pages.updateUser, true);
		 $id("txtUsernameUpdate").value=$id("profileUserName").innerText;
		 */
		if ($id("profilePanel").hasClass("hide")) {
			$id("profilePanel").removeClass("hide");
		} else {
			$id("profilePanel").addClass("hide");
		}

	});

	$id("profileChangePasswordBtnId").addEventListener("click", function(event) {
		event.preventDefault();
		showPage("updateUser",true);
		$id("txtUsernameUpdate").value = currentUserId;
	});

	$id("profileLogOutBtnId").addEventListener("click", function(event) {
		event.preventDefault();
		$id("txtUsernameUpdate").value = 'guest';
		$id("login").removeClass("hide");
		$id("profile").addClass("hide");
		$id("panel").addClass("hide");
		$id("profilePanel").addClass("hide");
		currentUserEmail="";
		ajax.get({
			url : "http://localhost:8080/book-service/public/book/authen/logout",
			success : function(data, xhr) {

			},
			failure : function(xhr) {
			},
			abort : function(xhr) {
				callback.abort(xhr);
			}
		});

	});

	$id("btnChangePassword").addEventListener("click", function() {
		//var textbox = document.getElementById("txtCmt");
		//var commentText = textbox.value;
		//var bookId = textbox.getAttribute("bookid");

		var oldPassword = document.getElementById("txtOldPaswordUpdate").value;
		var newPassword = document.getElementById("txtNewPasswordUpdate").value;
		var newPasswordConfirm = document.getElementById("txtNewPasswordConfirmUpdate").value;

		if (newPassword == newPasswordConfirm) {
			ajax.post({
				url : "http://localhost:8080/book-service/public/book/authen/changePassword",
				param : {
					"oldPassword" : oldPassword,
					"newPassword" : newPassword
				},

				success : function(data, xhr) {
					console.log(data);
					alert("update successful");
					hidePopup();

				},
				failure : function(xhr) {
					if (xhr.status == 401) {
						alert("you have no permission to change password, please re-log again!")
						hidePopup();
					} else if (xhr.status == 404) {
						alert("your userName or password is wrong, please check again");
					}
					console.log("fail");
				},
				abort : function(xhr) {
					callback.abort(xhr);
				}
			});
		} else {
			alert("password do not match, please try again");
		}
	});

	$id("changeYourAvatarBtnId").addEventListener("click", function(event) {
		event.preventDefault();
		showPage("updateAvatar",true);
		//get current avatar
		$id("currentAvatarId").src=$id("profilePicture").src;
	},false);
	
	$id("btnChangeAvatarId").addEventListener("click",function(event){
		event.preventDefault();
		var file = $id("txtFile").files[0];
		if(file){
		console.log($id("txtFile").files[0]);
		
		 var formData = new FormData();
		 	formData.append("file", file);
			formData.append("backendUrl", "http://localhost:8080/book-service/");
	  var xhr = new XMLHttpRequest();
	   xhr.withCredentials = true;
  		
  		
		xhr.onreadystatechange = function() {
			if (this.readyState == 4 && this.status == 200) {
				console.log('xhr.readyState=', this.readyState);
				console.log('xhr.status=', this.status);
				console.log('response=', this.responseText);

				var data = this.responseXML;
				console.log(data);
				var avatar = data.getElementsByTagName("avatar")[0].childNodes[0].nodeValue;
			
	   		$id("icon-avatar").src =avatar;
	        $id("profilePicture").src= avatar;
	        $id("icon-avatar").src =avatar;
	        
	        alert("cập nhật avatar thành công");
	        //hide currentPage;
	       hidePopup();
	        
			}
		}

  		 
  		 xhr.open('POST', "http://localhost:8080/book-service/user/changeAvatar", true);

  xhr.send(formData);
  }else{
  	alert("hãy chọn file ảnh bạn muốn up)");
  }  // multipart/form-data
	},false);




	$id("btnSendFeedBack").addEventListener("click", function(event){
		event.preventDefault;
		var email =$id("feedBackEmailId").value;
		var title =$id("txtTitleFeedbackId").value;
		var contents =$id("txtFeedbackContentId").value;
		
		if(email!=""&&title!=""&&contents!=""){
		
				ajax.post({
			url : "http://localhost:8080/book-service/public/feedback/add",
			param : {
				"email" : email,
				"title" : title,
				"contents" : contents
			},

			success : function(data, xhr) {
				console.log(data);

				alert("Cảm ơn bạn đã góp ý cho chúng tôi");
				hidePopup();	
				
			},
			failure : function(xhr) {
				console.log("fail");
			},
			abort : function(xhr) {
				callback.abort(xhr);
			}
		});
		}else{
			alert("Hãy điền đầy đủ thông tin. Cảm ơn");
		}
	});


}
